﻿using Hxj.Data;
using MsgCenter.Service.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Utility;
using Utility.Model;

namespace MsgCenter.Service
{
    public class WeChatService
    {
        public enum PushType
        {
            Notice,
            Consult
        }


        private static DbSession DefaultDb;
        /// <summary>
        /// 得到数据库对象
        /// </summary>
        /// <returns></returns>
        private static DbSession GetDatabase()
        {
            try
            {
                if (DefaultDb == null)
                {
                    DefaultDb = new DbSession("sqlConnRecruitStudents");  //默认连接
                }
            }
            catch (Exception ex)
            {
                throw new Exception("数据库连接初始化失败", ex);
            }
            return DefaultDb;
        }
        internal static void WeChatPushNotice()
        {
            string strSql = "select a.*,b.OpenID,c.Name from TB_Notice as a left join TB_SignUpStudents_Wechat_Mapping as b on a.SignUpID=b.SignUpID left join TB_SignUpStudents as c on a.SignUpID = c.SignUpID  where a.ispush=0 and a.NoticeType='private' ";
            using (DataTable dt = GetDatabase().FromSql(strSql).ToDataTable())
            {
                //WeChatPush(dt, PushType.Notice);
            }
        }

        private static void WeChatPush(DataTable dt, PushType pushType)
        {
            var wx = new WeChatHelper();
            if (pushType == PushType.Notice)
            {
                #region Notice 
                foreach (DataRow dr in dt.Rows)
                {
                    try
                    {
                        if (dr["NoticeTitle"].ToString().Contains("成绩已更新") && !dr["OpenID"].ToString().IsNullOrEmpty())
                        {
                            string strMessage = dr["Message"].ToString();
                            string[] strMessageS = strMessage.Split('。');
                            if (strMessageS.Length > 0)
                            {
                                strMessage = strMessageS[0];
                            }
                            string placeName = strMessage.Substring(0, 4);
                            string scoreMessage = strMessage.Replace("成绩已发布,请至网站或微信查询", "").Replace("成绩已发布,请至网站或App查询", "");
                            string examlevel = scoreMessage.Substring(scoreMessage.Length - 2, 2);
                            string spec = scoreMessage.Substring(4, scoreMessage.Length - 6);
                            var data = new
                            {
                                first = new { value = "你好，成绩已发布，请查询。" },
                                keyword1 = new { value = placeName },
                                keyword2 = new { value = spec },
                                keyword3 = new { value = examlevel },
                                keyword4 = new { value = DateTime.Now },
                                remark = new { value = strMessage + "..." }
                            };
                            wx.SendTemplete(AppConfigHelper.WxTempleteID_Score, dr["OpenID"].ToString(), data, AppConfigHelper.WxHome + "user/AuthNotice?DataID=" + dr["NoticeID"].ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        LogServiceHelper.WriteMessageError("Notice推送微信失败：", ex);
                    }
                    GetDatabase().FromSql("update TB_Notice set IsPush=1,CreateTime=getdate() where NoticeID='" + dr["NoticeID"].ToString() + "'").ExecuteNonQuery();
                }
                try
                {
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        //oQ57ovxXedOAMv6VdGWeCogN5Ajo
                        if (dr["NoticeTitle"].ToString().Contains("成绩已更新") && !dr["OpenID"].ToString().IsNullOrEmpty())
                        {
                            string strMessage = dr["Message"].ToString();
                            string[] strMessageS = strMessage.Split('。');
                            if (strMessageS.Length > 0)
                            {
                                strMessage = strMessageS[0];
                            }
                            string placeName = strMessage.Substring(0, 4);
                            string scoreMessage = strMessage.Replace("成绩已发布,请至网站或微信查询", "").Replace("成绩已发布,请至网站或App查询", "");
                            string examlevel = scoreMessage.Substring(scoreMessage.Length - 2, 2);
                            string spec = scoreMessage.Substring(4, scoreMessage.Length - 6);
                            var data = new
                            {
                                first = new { value = "你好，成绩已发布，请查询。" },
                                keyword1 = new { value = placeName },
                                keyword2 = new { value = spec },
                                keyword3 = new { value = examlevel },
                                keyword4 = new { value = DateTime.Now },
                                remark = new { value = strMessage + "..." }
                            };
                            wx.SendTemplete(AppConfigHelper.WxTempleteID_Score, "oQ57ovxXedOAMv6VdGWeCogN5Ajo", data, AppConfigHelper.WxHome + "user/AuthNotice?DataID=" + Guid.Empty);
                            wx.SendTemplete(AppConfigHelper.WxTempleteID_Score, "oQ57ov1k_Uj8jiVA_m9Dvu2nxsbo", data, AppConfigHelper.WxHome + "user/AuthNotice?DataID=" + Guid.Empty);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogServiceHelper.WriteMessageError("Notice推送王超马斌微信失败：", ex);
                }
                #endregion
            }
            else if (pushType == PushType.Consult)
            {
                #region Consult 
                foreach (DataRow dr in dt.Rows)
                {
                    try
                    {
                        if (!dr["OpenID"].ToSafeString().IsNullOrEmpty())
                        {
                            var data = new
                            {
                                first = new { value = dr["NoticeTitle"].ToString() },
                                keyword1 = new { value = dr["ConsultTitle"].ToString() },
                                keyword2 = new { value = dr["CreateDate"].ToString() },
                                remark = new { value = dr["Message"].ToString().ToLeft(20) + "..." }
                            };
                            wx.SendTemplete(AppConfigHelper.WxTempleteID_Consult, dr["OpenID"].ToString(), data, AppConfigHelper.WxHome + "user/AuthConsult?DataID=" + dr["ID"].ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        LogServiceHelper.WriteMessageError("Consult推送微信失败：", ex);
                    }
                }
                #endregion
            }
        }

        internal static void WeChatPushConsult()
        {
            string strSql = @"
               select b.ID,'您的问题已得到解答。' as NoticeTitle,b.ConsultTitle,c.Name,d.OpenID,b.ConsultContent as Message,a.CreateDate  from TB_ConsultReply as a 
                left join TB_ConsultTitle as b on a.TopicID=b.ID
                left join TB_SignUpStudents as c on b.UsersID=c.SignUpID
                left join TB_SignUpStudents_Wechat_Mapping as d on b.UsersID=d.SignUpID
                 where a.IsQuestions=0 and d.openId is not null 
                 and a.createDate >=(
	                select top 1 PushDate from TB_Push_Message where PushType=1
                ) 
                update TB_Push_Message set PushDate = getDate() where PushType = 1
                ";
            using (DataTable dt = GetDatabase().FromSql(strSql).ToDataTable())
            {
                WeChatPush(dt, PushType.Consult);
            }
        }
    }
}
